<style lang="less">
.tag-recommend {
    .recommend-list {
        position: relative;
        display: inline-block;
        margin: 10px;
        background-size: contain;
        background-repeat: no-repeat;
        background-position: center center;
        width: 100px;
        height: 100px;
        .label {
            position: absolute;
            top: 0;
            left: 0;
            color: #fff;
            width: 100%;
            padding: 2px;
            box-sizing: border-box;
            background-color: rgba(0, 0, 0, .5);
        }
        .image-item {
            display: none;
            padding: 2px 0;
            position: absolute;
            bottom: 0;
            width: 100%;
            background-color: rgba(0, 0, 0, .5);
            justify-content: space-around;
            align-items: center;

            img,a {
                width: 15px;
                height: 15px;
            }
        }
        &:hover {
            .image-item {
                display: flex;
            }
        }
    }
    .top-recommend-list {
        width: 200px;
        height: 150px;
    }
    .jump-url {
        width: 300px;
    }
}
</style>

<template>
    <div class="tag-recommend">
        <draggable
            @start="drag=true"
            @end="drag=false"
            v-model="itemsData">
            <div v-for="item in itemsData" class="recommend-list" :class="{'top-recommend-list': parseInt(type) === 1}" :style="getImage(item)">
                <p class="label">{{ item.title }}</p>
                <span class="image-item">
                    <img src="../../img/edit.png" @click="editItem(item)"/>
                    <router-link :to="'/keyword-materials/'+item.keyword_id">
                        <img src="../../img/management.png"/>
                    </router-link>
                    <img src="../../img/delete.png" @click="deleteItem(item)" />
                </span>
            </div>
        </draggable>
        <el-dialog :title="type === 'label_recommend' ? '添加标签推荐': '添加顶部推荐'" :visible.sync="ifVisible">
            <el-form :model="editData">
                <el-form-item label="关键词/ID">
                    <el-select
                        class="keyword-name"
                        v-model="editData.keyword_id"
                        filterable
                        remote
                        reserve-keyword
                        placeholder="请输入关键词或ID"
                        :remote-method="remoteMethod"
                        :loading="loading">
                        <el-option
                        v-for="item in options"
                        :key="item.id"
                        :label="item.keyword"
                        :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="推荐时间">
                    <DatePicker
                        v-model="editData.start_time"
                        type="datetime"
                        placeholder="选择开始日期">
                    </DatePicker>
                    <DatePicker
                        v-model="editData.end_time"
                        type="datetime"
                        placeholder="选择结束日期">
                    </DatePicker>
                </el-form-item>
                <el-form-item label="背景图片">
                    <Uploader
                        list-type="picture-card"
                        v-model="preview"
                        :width="imgWidth"
                        :height="imgHeight"
                    >
                        <i :class="[
                            preview
                                ? 'el-icon-edit'
                                : 'el-icon-plus'
                        ]"></i>
                        <div class="tips">{{ imgWidth }}*{{ imgHeight }}</div>
                    </Uploader>
                </el-form-item>
                <el-form-item label="跳转参数">
                    <el-select v-model="editData.redirect_type" class="jump-type">
                        <el-option
                            v-for="item in jumpTypes"
                            :label="item.jump_label"
                            :key="item.jump_type"
                            :value="item.jump_type"
                            :disabled="item.jump_label === '未找到匹配项'"
                        ></el-option>
                    </el-select>
                    <el-input v-model="editData.params" placeholder="跳转参数" class="jump-url"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="ifVisible=false">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import KeywordRecommendModel from '../../models/keyword-recommend';
import KeywordModel from '../../models/keyword';

// import JumpUrlsModel from '../../models/jump-url';
// import Promise from 'bluebird';

export default {
    props: {
        itemsData: {
            type: Array,
            default() {
                return [];
            }
        },
        type: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            ifVisible: false,
            options: [],
            loading: false,
            recommendQuery: {
                start_time: '',
                end_time: '',
                id: '',
                asset_url: '',
                width: '',
                height: '',
                redirect_type: 'global_router',
                url: '',
                params: '',
            },
            editData: {},

            jumpTypes: [{
                jump_type: 'global_router',
                jump_label: '全局路由'
            }, {
                jump_type: 'redirect',
                jump_label: '直接跳转'
            }],
            ifHasJumpParam: false,
            ifFirst: true,

            preview: null
        };
    },
    computed: {
        imgWidth() {
            return this.type === 'label_recommend' ? 270 : 210;
        },
        imgHeight() {
            return this.type === 'label_recommend' ? 270 : 210;
        }
    },
    components: {
        draggable: require('vuedraggable'),
        DatePicker: require('../date-picker')
    },
    watch: {
        // 'editData.jump_type': {
        //     handler: 'handleJumpUrl'
        // },
        preview: {
            deep: true,
            handler: 'handleImage'
        },
        itemsData(items) {
            this.items = items;
        }
    },
    methods: {
        getData() {
            return this.items;
        },
        getImage(item) {
            return {
                backgroundImage: 'url(' + item.asset_url + ')',
            };
        },
        // 当日
        getDateTime() {
            const todayM = new Date();
            const todayN = new Date();

            todayM.setHours(0);
            todayM.setMinutes(0);
            todayM.setSeconds(0);

            todayN.setHours(23);
            todayN.setMinutes(59);
            todayN.setSeconds(59);

            return {
                todayM,
                todayN
            };
        },
        deleteItem(item) {
            this.$emit('deleteItem', item);
        },
        editItem(item) {
            if(!item) {
                this.editData = Object.assign({}, this.recommendQuery, {
                    start_time: this.getDateTime().todayM,
                    end_time: this.getDateTime().todayN
                });
            }
            else {
                this.editData = item;
                this.preview = Object.assign({}, {
                    url: item.asset_url
                });
            }
            this.ifVisible = true;
        },
        // handleJumpUrl(newValue) {
        //     // 第一次不清空
        //     if(!this.ifFirst) {
        //         this.editData.jump_param = '';
        //     }
        //     this.ifFirst = false;

        //     const jumpTypes = this.jumpTypes;
        //     const jumpUrls = jumpTypes.find((el) => {
        //         return el.jump_type === newValue;
        //     });

        //     this.ifHasJumpParam = jumpUrls.jump_params > 0;
        //     this.jumpParamsTips = jumpUrls.jump_params_tips;
        // },
        handleImage(obj) {
            Object.assign(this.editData, {
                asset_url: obj.url,
                width: obj.width,
                height: obj.height
            });
        },
        save() {
            const params = Object.assign({}, { recommend_type: this.type }, this.recommendQuery, {banner: this.editData});
            if(!params.banner.asset_url) {
                this.$message({
                    message: '请上传预览图',
                    type: 'danger'
                });
            }

            if(!params.banner.keyword_id) {
                this.$message({
                    message: '请选择关键字',
                    type: 'danger'
                });
            }
            let $modelPromise = '';
            if(params.banner.id) {
                params.id = params.banner.id;
                $modelPromise = KeywordRecommendModel.update(params).$promise;
            }
            else {
                delete params['id'];
                $modelPromise = KeywordRecommendModel.save(params).$promise;
            }
            $modelPromise.then(res => {
                this.ifVisible = false;
                if(res.code && res.code !== 200) {
                    this.$message.error(res.message);
                }
                else {
                    this.$message({
                        message: '提交成功',
                        type: 'success'
                    });
                    this.editData = {};
                    this.preview = null;
                    this.recommendQuery = null;
                    this.$emit('loadItems');
                }
            })
            .catch(err => {
                this.$message.error(err);
            });
        },
        remoteMethod(query) {
            if(query !== '') {
                this.loading = true;
                const params = Object.assign({}, {
                    q: query
                }, this.keywordQuery);

                KeywordModel.query(params).$promise
                .then((res) => {
                    this.loading = false;
                    this.options = res.items;
                })
                .catch(err => {
                    this.$message.error(err);
                });
            }
            else {
                this.options = [];
            }
        }
    },
};
</script>
